<template>
  <Card>
      <p slot="title">
          审批复核
      </p>
      <Row type="flex" justify="center" align="middle">
          <Col span="3"> 复核结果
          </Col>
          <Col span="21">
          <Select v-model="resultOption" @on-change="resultOptionOnchange" label-in-value style="width:200px;">
              <Option v-for="item in resultOptions" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
          <!-- <Col span="6">
              资金来源
          </Col>
          <Col span="6">
              {{fundName}}
          </Col> -->
      </Row>
      <br>
      <Collapse value="1" v-if="resultOption == 'OK'">
          <Panel name="1">
              审批确认
              <p slot="content">
                <Form label-position="top">
                    <FormItem label="审批确认" class="labelWeightBold">
                        <CheckboxGroup v-model="approvalConfirms">
                            <Checkbox :label="child.opinionTypeCode" v-for="child in approvalConfirmsSelect" :key="child.id">
                                <span>{{child.opinionTypeName}}</span>
                            </Checkbox>
                        </CheckboxGroup>
                    </FormItem>
                    <FormItem label="审批意见" class="labelWeightBold">
                        <Input v-model="approvalOpinionContent" type="textarea" :autosize="{minRows: 5,maxRows: 5}" placeholder="请输入内容"></Input>
                    </FormItem>
                    <FormItem label="违例代码" class="labelWeightBold">
                      <Row>
                        <Col span="12">
                        <Select v-model="approvalViolationOne" style="width:300px" @on-change="violationOneChange" label-in-value>
                            <Option v-for="item in approvalViolationOneOptions" :value="item.opinionTypeCode" :key="item.id">{{ item.opinionTypeName }}</Option>
                        </Select>
                        </Col>
                        <Col span="12">
                        <Select v-model="approvalViolationTwo" style="width:300px" label-in-value>
                            <Option v-for="item in approvalViolationTwoOptions" :value="item.opinionTypeCode" :key="item.id">{{ item.opinionTypeName }}</Option>
                        </Select>
                        </Col>
                      </Row>
                    </FormItem>
                    <FormItem label="违例意见" class="labelWeightBold">
                        <Input v-model="approvalViolationOpinionContent" type="textarea" :autosize="{minRows: 5,maxRows: 5}" placeholder="请输入内容"></Input>
                    </FormItem>
                </Form>
              </p>
          </Panel>
      </Collapse>
      <Collapse value="1" v-if="resultOption == 'RETURN'">
          <Panel name="1">
              复核结果
              <p slot="content">
                <Form label-position="top">
                  <FormItem label="退回原因" class="labelWeightBold">
                    <Input v-model="returnReason" type="textarea" :autosize="{minRows: 5,maxRows: 5}" placeholder="请输入内容"></Input>
                  </FormItem>
                </Form>
              </p>
          </Panel>
      </Collapse>
      <Collapse value="1" v-if="resultOption == 'RETURN_APP'">
          <Panel name="1">
              复核结果
              <p slot="content">
                <Form label-position="top">
                    <FormItem label="退回原因大类" class="labelWeightBold">
                        <CheckboxGroup v-model="approvalReturnAppOpinions">
                            <Checkbox :label="child.opinionTypeCode" v-for="child in approvalReturnAppOpinionsSelect" :key="child.id">
                                <span>{{child.opinionTypeName}}</span>
                            </Checkbox>
                        </CheckboxGroup>
                    </FormItem>
                    <FormItem label="退补件意见" class="labelWeightBold">
                        <Input v-model="approvalReturnAppOpinionContent" type="textarea" :autosize="{minRows: 5,maxRows: 5}" placeholder="请输入内容"></Input>
                    </FormItem>
                </Form>
              </p>
          </Panel>
      </Collapse>
      <Collapse value="1" v-if="resultOption == 'REFUSE'">
          <Panel name="1">
              复核结果
              <p slot="content">
                <Form label-position="top">
                  <FormItem label="拒绝代码" class="labelWeightBold">
                    <div>
                      <Button type="info" size="small" @click="openOpinionsModal">选择拒绝意见</Button>
                    </div>
                    <Tag color="primary" v-for="item in choosedOpinionTypesLv3" :key="item.id" :name="item.opinionTypeCode">{{ item.opinionTypeName }}</Tag>
                  </FormItem>
                  <FormItem label="拒绝意见" class="labelWeightBold">
                      <Input v-model="approvalRefuseOpinionContent" type="textarea" :autosize="{minRows: 5,maxRows: 5}" placeholder="请输入内容"></Input>
                  </FormItem>
                </Form>
              </p>
          </Panel>
      </Collapse>
        <br>
        <div style="text-align:center">
            <Button type="primary" @click="saveOpinionBt" :disabled="taskParams.type!=1" >保存</Button>
            <Button type="primary" @click="complateOpinionBt" :disabled="taskParams.type!=1" >提交</Button>
        </div>
        <!-- <Table border :columns="approvalOpinionCols" :data="approvalOpinionDatas"></Table> -->
        <br>
        <Collapse value="1">
            <Panel name="1">
                审批流程
                <p slot="content">
                  <Timeline>
                      <TimelineItem v-for="(item,index) in approvalOpinionDatas" :key="item.node_name+'_'+index">
                          <p class="common-title">{{item.updatedDate}}</p>
                          <p class="common-title">{{item.nodeName}}</p>
                          <p class="common-content" v-if="item.caseResult=='OK'">复核结果：通过</p>
                          <p class="common-content" v-if="item.caseResult=='REFUSE'">复核结果：拒绝</p>
                          <p class="common-content" v-if="item.caseResult=='RETURN'">复核结果：退回</p>
                          <p class="common-content" v-if="item.caseResult=='RETURN_APP'">复核结果：退回前端</p>
                          <p class="common-content">类型名称：{{item.opinionTypeName}}</p>
                          <p class="common-content" v-if="item.opinionClass==3">复核意见：{{item.opinion}}</p>
                          <p class="common-content" v-if="item.opinionClass==1">违例意见：{{item.opinion}}</p>
                          <p class="common-content" v-if="item.opinionClass==0">拒绝意见：{{item.opinion}}</p>
                          <p class="common-content" v-if="item.opinionClass==4">退回APP意见：{{item.opinion}}</p>
                          <p class="common-content" v-if="item.opinionClass==5">退回意见：{{item.opinion}}</p>
                          <p class="common-content">处理人员：{{item.updatedBy}}</p>
                      </TimelineItem>
                  </Timeline>
                </p>
            </Panel>
        </Collapse>
        <modalRefuse :menuLv1List="approvalRefuseOpinionOneSelect" :data="choosedLv3" :display="modal1" @close="closeModal"></modalRefuse>
    </Card>
</template>

<script>
import modalRefuse from '../../components/modal-refuse-list.vue'

export default {
  name: 'loan-approval-form',
  components: {
    modalRefuse
  },
  data () {
    return {
      loanId: '',
      fundName: null,
      modal1: false,
      // 复核结果
      resultOption: null,
      resultOptions: [
        {
          label: '通过',
          value: 'OK'
        },
        {
          label: '退回',
          value: 'RETURN'
        },
        {
          label: '退回到前端',
          value: 'RETURN_APP'
        },
        {
          label: '拒绝',
          value: 'REFUSE'
        }
      ],
      approvalOpinionCols: [
        {
          type: 'index'
        },
        {
          title: '流程阶段',
          key: 'nodeName'
        },
        {
          title: '处理结果',
          key: 'caseResult'
        },
        {
          title: '处理意见',
          key: 'opinion'
        },
        {
          title: '处理人',
          key: 'createdBy'
        },
        {
          title: '处理时间',
          key: 'endTimeForMat'
        }
      ],
      approvalOpinionDatas: [],
      // 审批确认 ， 审批结果
      approvalConfirms: [],
      approvalConfirmsSelect: [],
      approvalOpinionContent: null,
      // 违例
      approvalViolationOne: null,
      approvalViolationOneOptions: [],
      approvalViolationTwo: null,
      approvalViolationTwoOptions: [],
      approvalViolationOpinionContent: null,
      returnReason: null, // 退回原因
      // 退回APP
      approvalReturnAppOpinions: [],
      approvalReturnAppOpinionsSelect: [],
      approvalReturnAppOpinionContent: null,
      // 拒绝
      approvalRefuseOpinionContent: null,
      approvalRefuseOneOpinions: [],
      approvalRefuseOpinionOneSelect: [],
      approvalRefuseTwoOpinions: [],
      approvalRefuseOpinionTwoSelect: [],
      approvalRefuseThrOpinions: [],
      approvalRefuseOpinionThrSelect: [],
      approvalRefuseOpinions: [],
      choosedLv3: [], // 选中的三级菜单选项
      choosedOpinionTypesLv3: [] // 选中的三级菜单对象
    }
  },
  methods: {
    // 保存
    saveOpinionBt () {
      if (!this.resultOption) {
        this.$Message.warning('请选择审批结果')
        return
      }
      var params = this.setParams()
      this.$ajax.post(this.$appContext.marvels_core_approve + 'approve/approval/service/addapproval', params).then(re => {
        if (re.data.code === 'success') {
          this.$Message.success({ title: '提示', content: re.data.data.loanId + '保存成功!', onOk () { } })
          // vm.query_status_num();
        } else {
          this.$Message.warning({ title: '提示', content: re.data.data.loanId + '保存失败', onOk () { } })
        }
      }).catch(er => {
        // console.log(er)
      })
    },
    setParams () {
      var params = {}
      params.loanId = this.loanId
      params.processResult = this.resultOption
      // 审批确认
      var processOpinions = []
      if (this.approvalConfirms.length !== 0) {
        for (let i = 0; i < this.approvalConfirms.length; i++) {
          processOpinions.push({ opinionTypeCode: this.approvalConfirms[i] })
        }
      }
      params.processOpinions = processOpinions
      // 违例代码
      params.violationOpinion = this.approvalViolationTwo
      // 违例意见
      params.violationOptionContent = this.approvalViolationOpinionContent
      // 退回大类
      var returnAppOpinions = []
      if (this.approvalReturnAppOpinions.length !== 0) {
        for (let i = 0; i < this.approvalReturnAppOpinions.length; i++) {
          returnAppOpinions.push({ opinionTypeCode: this.approvalReturnAppOpinions[i] })
        }
      }
      params.returnAppOpinions = returnAppOpinions
      // 退回大类原因
      params.returnAppOpinionContent = this.approvalReturnAppOpinionContent
      // 拒绝代码
      var refuseOpinionTypes = []
      for (let i = 0; i < this.choosedOpinionTypesLv3.length; i++) {
        refuseOpinionTypes.push({ opinionTypeCode: this.choosedOpinionTypesLv3[i].opinionTypeCode })
      }
      params.refuseOpinionTypes = refuseOpinionTypes
      if (params.processResult === 'OK') {
        // 审批意见
        params.opinionContent = this.approvalOpinionContent
      } else if (params.processResult === 'REFUSE') {
        // 拒绝意见
        params.opinionContent = this.approvalRefuseOpinionContent
      } else if (params.processResult === 'RETURN') {
        // 退回原因
        params.opinionContent = this.returnReason
      }
      return params
    },
    opinionSubmitDatas (approvalOpinion, approvalOpinionSelect) {
      var result = []
      approvalOpinion.forEach(item => {
        approvalOpinionSelect.forEach(selectItem => {
          if (selectItem.opinionTypeCode === item) {
            result.push(selectItem)
          }
        })
      })
      return result
    },
    handleSubmit (params) {
      var config = {
        title: '提示',
        content: '是否确认提交?',
        onOk: () => {
          this.doSubmit(params)
        }
      }
      this.$Modal.confirm(config)
    },
    // 完成
    complateOpinionBt () {
      if (!this.resultOption) {
        this.$Message.warning('请选择审批结果')
        return
      }
      var params = this.setParams()
      var validate = this.validSubmitData(params)
      if (validate) {
        this.handleSubmit(params)
      }
    },
    doSubmit (params) {
      this.$ajax.post(this.$appContext.marvels_core_approve + 'approve/approval/service/complateapproval', params).then(re => {
        if (re.data.code === 'success') {
          this.$Message.success({ title: '提示', content: re.data.data.loanId + '提交复核成功!', onOk () { } })
          this.$router.back()
        } else {
          this.$Message.warning({ title: '提示', content: re.data.data.loanId + '提交复核失败!', onOk () { } })
        }
      }).catch(er => {
      })
    },
    // 校验提交数据
    validSubmitData (params) {
      var flag = true
      if (params.processResult === 'OK') {
        if (!params.processOpinions || params.processOpinions.length < 1) {
          this.$Message.warning('审批确认选项不能为空')
          flag = false
        }
      } else if (params.processResult === 'RETURN') {
        if (!params.opinionContent || params.opinionContent == null || params.opinionContent === '') {
          this.$Message.warning('退回原因不能为空')
          flag = false
        }
      } else if (params.processResult === 'RETURN_APP') {
        if (!params.returnAppOpinions || params.returnAppOpinions.length < 1) {
          this.$Message.warning('退回原因选项不能为空')
          flag = false
        }
      } else if (params.processResult === 'REFUSE') {
        if (!params.refuseOpinionTypes || params.refuseOpinionTypes.length < 1) {
          this.$Message.warning('拒绝意见选项不能为空')
          flag = false
        }
      }
      return flag
    },
    // 加载审批结果
    loadFormData (data) { // 0 拒绝  1违例  2复核意见 3审批确认   4退回app  5退回上个流程
      var vm = this
      if (data && data.length > 0) {
        var opinion = data[0]
        vm.resultOption = opinion.caseResult
        if (opinion.caseResult === 'OK') { // 通过
          data.forEach(item => {
            if (item.opinionClass === 3) { // 渲染审批确认checkbox
              vm.approvalOpinionContent = item.opinion
              vm.approvalConfirms.push(item.opinionTypeCode)
            } else if (item.opinionClass === 1) { // 渲染违例代码
              vm.approvalViolationOpinionContent = item.opinion
              for (let i = 0; i < vm.approvalViolationOneOptions.length; i++) { // 一级违例代码列表
                let violationOptionsLv2 = vm.approvalViolationOneOptions[i].opinionTypes
                for (let j = 0; j < violationOptionsLv2.length; j++) { // 二级违例代码列表
                  if (item.opinionTypeCode === violationOptionsLv2[j].opinionTypeCode) {
                    vm.approvalViolationOne = violationOptionsLv2[j].opinionSupCode
                    vm.approvalViolationTwoOptions = violationOptionsLv2
                    vm.approvalViolationTwo = item.opinionTypeCode
                    return
                  }
                }
              }
            }
          })
        } else if (opinion.caseResult === 'RETURN') {
          vm.returnReason = opinion.opinion
        } else if (opinion.caseResult === 'RETURN_APP') { // 退回到前端
          vm.approvalReturnAppOpinionContent = opinion.opinion
          data.forEach(item => {
            vm.approvalReturnAppOpinions.push(item.opinionTypeCode)
          })
        } else if (opinion.caseResult === 'REFUSE') { // 拒绝
          vm.approvalRefuseOpinionContent = opinion.opinion
          vm.choosedLv3 = [] // 选中的三级菜单
          data.forEach(item => {
            vm.choosedLv3.push(item.opinionTypeCode)
          })
        }
      }
    },
    // 违例one
    violationOneChange (option) {
      var value = option.value
      this.approvalViolationOneOptions.forEach(item => {
        if (value === item.opinionTypeCode) {
          this.approvalViolationTwoOptions = item.opinionTypes
        }
      })
    },
    // 拒绝one
    approvalRefuseOpinionOneSelectChange (opinionTypes) {
      this.approvalRefuseOpinionTwoSelect = []
      this.approvalRefuseOpinionOneSelect.forEach(item => {
        let itemCode = item.opinionTypeCode
        var oneItem = item.opinionTypes
        opinionTypes.forEach(item => {
          if (itemCode === item) {
            this.approvalRefuseOpinionTwoSelect = this.approvalRefuseOpinionTwoSelect.concat(oneItem)
          }
        })
      })
    },
    // 拒绝two
    approvalRefuseOpinionTwoSelectChange (opinionTypes) {
      this.approvalRefuseOpinionThrSelect = []
      this.approvalRefuseOpinionTwoSelect.forEach(item => {
        let itemCode = item.opinionTypeCode
        var oneItem = item.opinionTypes
        opinionTypes.forEach(item => {
          if (itemCode === item) {
            this.approvalRefuseOpinionThrSelect = this.approvalRefuseOpinionThrSelect.concat(oneItem)
          }
        })
      })
    },
    openOpinionsModal () {
      if (this.resultOption === 'REFUSE') {
        this.modal1 = true
      }
    },
    closeModal (choosedData) {
      this.modal1 = false
      this.choosedOpinionTypesLv3 = choosedData
    },
    // 初始化
    initData () {
      var params = {}
      var vm = this
      params.loanId = this.loanId
      this.$ajax.post(this.$appContext.marvels_core_approve + 'approve/approval/service/qapproval', params).then(re => {
        if (re.data.code === 'success') {
          // 当前单据类型：是线上还是线下
          var patternCode = re.data.data.loanApplyCase.patternCode
          let approveRst = re.data.data.loanApplyCase.approveRst
          if (approveRst === 'RJ') {
            var resultOptionsTemp = [{
              label: '退回',
              value: 'RETURN'
            },
            {
              label: '拒绝',
              value: 'REFUSE'
            }]
            vm.resultOptions = resultOptionsTemp
          }
          // 审批确认
          vm.approvalConfirmsSelect = re.data.data.opinionTypes[3] || []
          // 违例代码
          var approvalViolationOneOptions = re.data.data.opinionTypes[1] || []
          approvalViolationOneOptions.forEach(item => {
            if (item.patternCode === patternCode) {
              vm.approvalViolationOneOptions.push(item)
            }
          })
          // 退回APP原因大类
          vm.approvalReturnAppOpinionsSelect = re.data.data.opinionTypes[4] || []
          // 拒绝代码
          vm.approvalRefuseOpinionOneSelect = []

          var checkOpinionDatas = re.data.data.opinionTypes[0] || []
          // 获取当前单据类型的拒绝列表
          checkOpinionDatas.forEach(item => {
            if (item.patternCode === patternCode) {
              vm.approvalRefuseOpinionOneSelect.push(item)
            }
          })
          // 初始化
          vm.initApprovalLogDatas(re.data.data.logs)
          vm.loadFormData(re.data.data.opinions)
        } else {
          vm.$Message.warning({ title: '提示', content: re.data.data.loanId, onOk () { } })
        }
      }).catch(er => {
      })
    },
    initApprovalLogDatas (list) {
      // approvalLogDatas
      var vm = this
      list.forEach(item => {
        item.updatedDate = this.$util.formatTime(new Date(item.updatedDate))
        for (let i = 0; i < vm.resultOptions.length; i++) {
          if (vm.resultOptions[i].value === item.caseResult) {
            item.caseResultName = vm.resultOptions[i].label
          }
        }
        this.approvalOpinionDatas.push(item)
      })
    },
    resultOptionOnchange () {
      // 审批确认 ， 审批结果
      this.approvalConfirms = []
      this.approvalOpinionContent = null
      // 违例
      this.approvalViolationOne = null
      this.approvalViolationTwo = null
      this.approvalViolationOpinionContent = null
      // 退回APP
      this.approvalReturnAppOpinions = []
      this.approvalReturnAppOpinionContent = null
      // 拒绝
      this.approvalRefuseOneOpinions = []
      this.approvalRefuseTwoOpinions = []
      this.approvalRefuseThrOpinions = []
      this.approvalRefuseOpinionContent = null
      this.choosedOpinionTypesLv3 = []
    }
  },
  computed: {

  },
  mounted () {

  },
  created () {
    this.loanId = this.taskParams.curLoanId
    this.$ajax = this.$util.ajax()
    // this.initData();
  },
  watch: {
    // 点击tab页签，加载数据，只加载一次
    'taskParams.approvalResult' (v) {
      if (v) {
        this.loanId = this.taskParams.curLoanId
        this.initData()
      }
    }
  },

  props: {
    taskParams: Object
  }
}
</script>
<style>
.common-title{
    font-size: 14px;
    font-weight: bold;
}
.common-content{
    padding-left: 5px;
}
</style>
